package com.mobipe.sutto.netty;

import java.nio.ByteBuffer;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.mobipe.sutto.core.AbstractServer;
import com.mobipe.sutto.core.InterfaceServerHandler;
import com.mobipe.sutto.core.ProtocolProcess;

/**
 * @author kohachiro
 *
 */
public class ServerHandler extends SimpleChannelUpstreamHandler implements InterfaceServerHandler{
	public static  InterfaceServerHandler callbackHandler;
	
	public ServerHandler(){
		AbstractServer.callbackHandler=this;
	}
	@Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception{
		ProtocolProcess.protocolHandler(((ChannelBuffer)e.getMessage()).toByteBuffer(), e.getChannel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getChannel().close();
    }

	@Override
	public void sendResponse(ByteBuffer message, Object channel) throws Exception {
    	ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    	buf.writeBytes(message);		
		((Channel)channel).write(buf);
	}
	@Override
	public void sendResponseClose(ByteBuffer message, Object channel) throws Exception {
    	ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    	buf.writeBytes(message);
    	((Channel)channel).write(buf).addListener(ChannelFutureListener.CLOSE);		
	}
	@Override
	public int getId(Object channel) {
		return ((Channel)channel).getId();
	}		
}
